package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;
    //保存
    @Override
    public void save(Address address) {
        //设置缺少的参数
        address.setUserId(UserHolder.get().getId());
        address.setIsDefault(0);    //0表示非默认地址
        //添加
        addressMapper.insert(address);
    }
    //列表查询
    @Override
    public List<Address> findList() {
        //设置查询条件：本用户id下的列表
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId,UserHolder.get().getId());
        List<Address> addressList = addressMapper.selectList(wrapper);
        return addressList;
    }
    //主键查询
    @Override
    public Address findById(Long id) {
        return addressMapper.selectById(id);
    }
    //修改
    @Override
    public void update(Address address) {
        addressMapper.updateById(address);
    }
    //删除
    @Override
    public void delete(List<Long> ids) {
        if(CollectionUtil.isNotEmpty(ids)) {
            addressMapper.deleteBatchIds(ids);
        }
    }
    //设置默认地址
    @Override
    public void setDefault(Long id) {
        //1.将该用户的所有地址设置为非默认
        //1.1创建对象
        Address address = new Address();
        address.setIsDefault(0);
        //1.2设置条件
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId,UserHolder.get().getId());
        //1.3修改
        addressMapper.update(address,wrapper);
        //2.根据id设置默认地址
        Address address1 = new Address();
        address1.setId(id);
        address1.setIsDefault(1);
        addressMapper.updateById(address1);

    }
    //条件查询
    @Override
    public ResultInfo findDefault() {
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId,UserHolder.get().getId())
                .eq(Address::getIsDefault,1);
        Address address = addressMapper.selectOne(wrapper);
        if (address != null) {
            return ResultInfo.success(address);
        } else {
            return ResultInfo.error("该用户未设置默认地址");
        }
    }
}
